/*
 * @Author: BF-202204111659\Administrator qiutengda@dingtalk.com
 * @Date: 2022-06-13 09:16:04
 * @LastEditors: tengda.qiu qiutengda@dingtalk.com
 * @LastEditTime: 2022-10-25 16:57:17
 * @FilePath: \uni-H5\src\request\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import appUtil from "../appUtil.js";
import useAiStore from '../../../../store/ai'; //vuex
const store = useAiStore();

// yuanbing 2022.10.25 注释掉, 暂时不需要上报
// import { postLog } from '../../serve';
import getRequestUrl from './getRequestUrl.js';
import getSnapScreenRequestUrl from './getSnapScreenRequestUrl.js';
let server_url = getRequestUrl.requestUrl;
let snapscreen_server_url = getSnapScreenRequestUrl.requestUrl;
// const dsbridge = require("../utils/dsbridge");
console.log('getRequestUrl', getRequestUrl.requestUrl)
const isProduction = import.meta.env.NODE_ENV === 'production'
// #ifdef H5
import loading from '../loading'
// #endif
let Authentication = '';
let storeID = 77 // yuanbin 20250502 阿坝小程序固定id
// import.meta.env.NODE_ENV === 'development' ? server_url = url_all['DEV'] : server_url = url_all['BUILD'];

function service(options = {}) {
    store.$state.Authentication && (Authentication = store.$state.Authentication);
    switch(options.serverType) {
        case 'download': // 下载图片服务
            options.url =  `${snapscreen_server_url}${options.url}`
            options.timeout = 150000
            break;
        default:
            options.url =   `${server_url}${options.url}`;
    }
    if (options.loading) {
        uni.showLoading({
            title: '加载中'
        });
    }
    options.data = options.params;
    options.timeout = options.timeout || 20000
    options.header = {
        // #ifdef MP-WEIXIN
        storeId: options.storeId ?? storeID, // 视旅
        'deviceId': uni.getStorageSync("Uuid"),
        // #endif

        // #ifdef H5
        'os': '',
        // #endif
        // 'content-type': 'application/x-www-form-urlencoded',	
        // 'content-type':'application/json',
        'Authentication': `${Authentication}`
    };

    if (options.contentType){
        options.header['content-type'] = options.contentType
    }
    
    return new Promise((resolved, rejected) => {
        let requestTime = Number(new Date())// 请求时间戳
        options.success = (res) => {
            let responseTime =  Number(new Date());
            let timeNum = responseTime - requestTime
            if (res.data.errCode == "C0302" || res.data.errCode == "C0222" || res.data.errCode == "C0220") {
                uni.removeStorageSync('Authentication')//登录失效清除缓存
                store.SET_TOKEN('')//登录失效清除store
                appUtil.needLogin()
            }
            if(res.data.errCode === 'P0200'){
                uni.showToast({
                    title: res.data.errMsg,
                    duration: 1000,
                    icon: "none",
                });
                setTimeout(() => {
                    uni.navigateBack()
                },2000)
            }
            let isRequ = options.url.indexOf('node/log/log/writeError') == -1 && server_url.indexOf('pre') == -1
            if (!res.data.success && res.data.resultCode !== 0 && isRequ && isProduction) {
                let logObj = {
                    type: 'weixin',
                    // data: res.data,
                    data: {
                        reqOption: options.data,
                        errData: res.data
                    },
                    resHeader: res.header,
                    storeID,
                    reqUrl: options.url,
                    requestTime: requestTime, // 请求时间戳
                    responseTime: responseTime,
                    reqTimeNumber: timeNum 
                }
                // postLog(logObj) yuanbing 2022.10.25 注释掉, 暂时不需要上报
            } else {
              if(timeNum > 500 & isRequ) {
                let logObj = {
                    type: 'weixin',
                    data: {
                        reqOption: options.data,
                        errData: res.data
                    },
                    resHeader: res.header,
                    storeID,
                    reqUrl: options.url,
                    requestTime: requestTime, // 请求时间戳
                    responseTime: responseTime,
                    reqTimeNumber: timeNum 
                }
                // postLog(logObj) yuanbing 2022.10.25 注释掉, 暂时不需要上报
              }
            }
            
            // 约定 C0301 弹出toast错误提示
            if(!res.data.success && res.data.errCode === 'C0301') {
                uni.showToast({
                    title: res.data.errMsg,
                    duration: 2000,
                    icon: "none",
                });
            }

            resolved(res.data);
            // #ifdef H5
            loading.hide()
            // #endif
            return res.data

        }
        options.fail = (err) => {
            //Do something with request error
            // #ifdef H5
            loading.hide()
            // #endif
            // postLog(err)
            let responseTime =  Number(new Date());
            let timeNum = responseTime - requestTime
            console.log('请求出错', err)
            let isRequ = options.url.indexOf('node/log/log/writeError') == -1 && server_url.indexOf('pre') == -1
            if (isRequ && isProduction) {
                let logObj = {
                    type: 'weixin',
                    data: {
                        reqOption: options.data,
                        errData: err
                    },
                    resHeader: {},
                    storeID,
                    reqUrl: options.url,
                    requestTime: requestTime, // 请求时间戳
                    responseTime: responseTime,
                    reqTimeNumber: timeNum 
                }
                // postLog(logObj) yuanbing 2022.10.25 注释掉, 暂时不需要上报
            }
            rejected(err)
        }
        options.complete = (op) => {
            if (options.loading) {
                uni.hideLoading();
            }
            // 埋点接口不需要超时提示
            const reg = /\/spm$/
            if (reg.test(options.url)) {
                return
            }
            if (op.errMsg == "request:fail timeout") {
                uni.showToast({
                    title: "链接超时，请稍后重试~",
                    icon: "none",
                })
                return
            }
        }
        // #ifdef H5
        loading.show()
        // #endif
        uni.request(options);
        uni.request
    });
}
export default service;